use serde::{Deserialize, Serialize};
use std::env;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub server: ServerConfig,
    pub database: DatabaseConfig,
    pub fluvio: FluvioConfig,
    pub ai: AiConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub cors_origins: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    pub url: String,
    pub max_connections: u32,
    pub min_connections: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FluvioConfig {
    pub cluster_endpoint: String,
    pub default_partitions: u32,
    pub default_replication: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiConfig {
    pub openai_api_key: Option<String>,
    pub model: String,
    pub max_tokens: u32,
}

impl Config {
    pub fn from_env() -> anyhow::Result<Self> {
        Ok(Config {
            server: ServerConfig {
                host: env::var("SERVER_HOST").unwrap_or_else(|_| "0.0.0.0".to_string()),
                port: env::var("SERVER_PORT")
                    .unwrap_or_else(|_| "8080".to_string())
                    .parse()?,
                cors_origins: env::var("CORS_ORIGINS")
                    .unwrap_or_else(|_| "http://localhost:3000".to_string())
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .collect(),
            },
            database: DatabaseConfig {
                url: env::var("DATABASE_URL")
                    .unwrap_or_else(|_| "postgresql://postgres:password@localhost:5432/fluviox".to_string()),
                max_connections: env::var("DB_MAX_CONNECTIONS")
                    .unwrap_or_else(|_| "10".to_string())
                    .parse()?,
                min_connections: env::var("DB_MIN_CONNECTIONS")
                    .unwrap_or_else(|_| "1".to_string())
                    .parse()?,
            },
            fluvio: FluvioConfig {
                cluster_endpoint: env::var("FLUVIO_CLUSTER")
                    .unwrap_or_else(|_| "localhost:9003".to_string()),
                default_partitions: env::var("FLUVIO_DEFAULT_PARTITIONS")
                    .unwrap_or_else(|_| "1".to_string())
                    .parse()?,
                default_replication: env::var("FLUVIO_DEFAULT_REPLICATION")
                    .unwrap_or_else(|_| "1".to_string())
                    .parse()?,
            },
            ai: AiConfig {
                openai_api_key: env::var("OPENAI_API_KEY").ok(),
                model: env::var("AI_MODEL")
                    .unwrap_or_else(|_| "gpt-3.5-turbo".to_string()),
                max_tokens: env::var("AI_MAX_TOKENS")
                    .unwrap_or_else(|_| "1000".to_string())
                    .parse()?,
            },
        })
    }
}
